package controller;

import java.io.IOException;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Articles;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;


public class ListArchivesServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setCharacterEncoding("utf-8");
		String path = ((HttpServletRequest)req).getRequestURI();
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 

        if(count != 2)
        {
        	resp.setStatus(301);
        	resp.sendRedirect("/");
        	return;
        }
        
		// skip one token /question/abcd (remove sites)
		st.nextToken();
		String title_url = st.nextToken();
		
		System.out.println(title_url);
		try {
			ObjectifyService.register(Articles.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		Objectify objectify = ObjectifyService.begin();
		try {
			Query<Articles> list = objectify.query(Articles.class).filter("strdate", title_url).order("-date").limit(200);
			
			req.setAttribute("list", list);
		} catch (Exception e) {
			resp.setStatus(301);
        	resp.sendRedirect("/");
        	return;
		}
		
		try {
			req.getRequestDispatcher("/list_archives.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
